package cn.itsource.product.controller;

import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.PageResult;
import cn.itsource.product.domain.Product;
import cn.itsource.product.domain.ProductDetail;
import cn.itsource.product.query.ProductQuery;
import cn.itsource.product.service.IProductDetailService;
import cn.itsource.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {


    @Autowired
    private IProductService productService;


    @Autowired
    private IProductDetailService productDetailService;
    @GetMapping
    public List<Product> findAll(){
        return productService.query();
    }


    /*
        批量上架
            前端给过的数组 [56,55,54,53]
            后台对应的接收形式 可以是数组 可以是 集合
     */
    @PatchMapping
    public AjaxResult deletePatch(@RequestBody List<Long> ids){
        try {
            productService.onSale(ids);
        } catch (Exception e) {
            return new AjaxResult(e.getMessage());
        }
        return new AjaxResult();
    }
 

    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Product product){
        System.out.println(product);
        try {
            if (product.getId()==null){
                productService.save(product);
            }else {
                productService.update(product);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
        return new AjaxResult();
    }
    @PostMapping
    public PageResult<Product> findAll(@RequestBody ProductQuery query){
        System.out.println(query);
        return productService.queryPage(query);
    }
    @PostMapping("/list")
    public PageResult<Product> findOnsale(@RequestBody ProductQuery query){
        query.setState(1);
        return productService.queryPage(query);
    }




    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            productService.delete(id);
        } catch (Exception e) {
            return new AjaxResult(e.getMessage());
        }
        return new AjaxResult();
    }


    @GetMapping("/detail/{id}")
    public ProductDetail detail(@PathVariable("id") Long id){
        return productDetailService.queryById(id);
    }
    @GetMapping("/pro/{id}")
    public Product pro(@PathVariable("id") Long id){
        return productService.queryById(id);
    }

}
